package com.xiaoning.sun.spring.mvc.controller;

import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.xiaoning.sun.spring.mvc.model.LoginForm;
import com.xiaoning.sun.spring.mvc.validator.LoginValidator;

@Controller
@RequestMapping(produces = { "application/json;charset=utf-8" })
public class LoginController{
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	LoginValidator loginValidator;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(loginValidator);
	}
	
	@RequestMapping("/login/welcome")
	protected ModelAndView onSubmit(Object command) throws ServletException {
	  ModelAndView modelAndView = new ModelAndView();
	  modelAndView.addObject("name", "Hello userName"); 
	  modelAndView.setViewName("success");
	  logger.info("/login/welcome");
	  return modelAndView;
	  
	  }
	
	@RequestMapping("/index")
	public ModelAndView initLogin(){
		ModelAndView modelAndView = new ModelAndView();
		LoginForm login = new LoginForm();
		modelAndView.addObject("loginForm", login);
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping("/login")
	public ModelAndView authLogin(@ModelAttribute("loginForm") @Validated LoginForm loginForm,BindingResult result, Model model){
		ModelAndView modelAndView = new ModelAndView();
		//TODO
		logger.info("userName:" + loginForm.getUserName());
		logger.info("password:" + loginForm.getPassword());
		modelAndView.addObject("userName",loginForm.getUserName());
		if(result.hasErrors()){
			modelAndView.setViewName("login");
		}else{
			modelAndView.setViewName("success");
		}
		
		return modelAndView;
	}
	@RequestMapping("/success")
	public String loginSuccess(Model model){
		ModelAndView modelAndView = new ModelAndView();
		//TODO
		modelAndView.addObject("userName","Login success");
		logger.info("access success page directly");
		return "success";
	}

}
